package drds.common.db.xml_mapping.executor.statement;


import drds.common.db.xml_mapping.executor.Executor;
import drds.common.db.xml_mapping.executor.key_generator.AutoSetModePrimaryKeyGenerator;
import drds.common.db.xml_mapping.executor.key_generator.PrimaryKeyGenerator;
import drds.common.db.xml_mapping.mapping.BindSql;
import drds.common.db.xml_mapping.mapping.Mapper;
import drds.common.db.xml_mapping.session.ResultHandler;
import drds.common.db.xml_mapping.session.RowBounds;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;


public class SimpleStatementHandler extends BaseStatementHandler {

  public SimpleStatementHandler(Executor executor, Mapper MappedStatement, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BindSql bindSql) {
    super(executor, MappedStatement, parameter, rowBounds, resultHandler, bindSql);
  }

  @Override
  public int update(Statement statement) throws SQLException {
    String sql = bindSql.getSql();
    Object parameterObject = bindSql.getParameterObject();
    PrimaryKeyGenerator primaryKeyGenerator = mappedStatement.getPrimaryKeyGenerator();
    int rows;
    if (primaryKeyGenerator instanceof AutoSetModePrimaryKeyGenerator) {
      statement.execute(sql, Statement.RETURN_GENERATED_KEYS);
      rows = statement.getUpdateCount();
      primaryKeyGenerator.generate(executor, mappedStatement, statement, parameterObject);
    } else {
      statement.execute(sql);
      rows = statement.getUpdateCount();
    }
    return rows;
  }

  @Override
  public void batch(Statement statement) throws SQLException {
    String sql = bindSql.getSql();
    statement.addBatch(sql);
  }

  @Override
  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    String sql = bindSql.getSql();
    statement.execute(sql);
    return resultSetHandler.handleResultSets(statement);
  }


  @Override
  protected Statement instantiateStatement(Connection connection) throws SQLException {
    return connection.createStatement();
  }

  @Override
  public void parameterize(Statement statement) {

  }

}
